package com.coldworks.coldjoke.task;

import java.io.IOException;
import java.util.List;

import android.content.Context;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import com.coldworks.base.BaseThread;
import com.coldworks.base.manager.BaseNetworkManager;
import com.coldworks.coldjoke.manager.UserManager;
import com.coldworks.coldjoke.model.UserModel;
import com.coldworks.coldjoke.util.NetworkUtil;

public class TopicReplyTask extends BaseThread {

	private Context context;
	private String url;
	private List<NameValuePair> param;

	public TopicReplyTask(Context context, String url, List<NameValuePair> params) {
		this.context = context;
		this.url = url;
		this.param = params;
	}

	@Override
	public void run() {
		HttpPost httpPost = new HttpPost(url);
		HttpParams httpParams = new BasicHttpParams();
		try {
			String sessionId = UserManager.getInstance().getSessionId();
			HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
			httpPost.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8));
			httpPost.setHeader("Cookie", "webpy_session_id=" + sessionId);
			HttpResponse response = BaseNetworkManager.getInstance()
					.createHttpClient(context).execute(httpPost);
			if (isInterrupted()) {
				log.info("cancelled");
				return;
			}
			if (response.getStatusLine().getStatusCode() == 200) {
				Header contentEncoding = response
						.getFirstHeader("Content-Encoding");
				JSONObject jsonObject = null;
				if (contentEncoding != null
						&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
					jsonObject = NetworkUtil.getInstance().getJsonObjectByGzip(
							response.getEntity().getContent());
				} else {
					jsonObject = NetworkUtil.getInstance().getJSONObject(
							response.getEntity().getContent());
				}
				if (jsonObject == null) {
					return;
				}
				if (jsonObject.getString("success").equals("true")) {
					UserModel userInfo = new UserModel();
					userInfo.setUserIcon(jsonObject
							.getString("author_cover_url"));
					userInfo.setUserId(jsonObject.getString("author_user_id"));
					userInfo.setUserName(jsonObject
							.getString("author_user_name"));
					return;
				}
				return;
			} else {
				log.info(String.valueOf(response.getStatusLine()
						.getStatusCode()));
				return;
			}
		} catch (ClientProtocolException e) {
			log.error("", e);
		} catch (IOException e) {
			log.error("", e);
		} catch (JSONException e) {
			log.error("", e);
		}
	}

}
